package com.xb.loan.cashier.biz.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 客户端的系统属性配置类
 * 注:使用Config时，所有key都需要在Const中配置为常量
 * @ClassName: Configure
 * 
 * @author lottery
 * 
 */
public class Configure {
	private static Map<String, Map<String, Object>> configMap = new HashMap<String, Map<String, Object>>();
	private static final String defaultConfig = "config/cashier_config.properties";
	private static ReadWriteLock lock = new ReentrantReadWriteLock();
	
	static {
		// 初始化系统配置信息
		init(defaultConfig);
	}

	private static void init(String configName){
		lock.writeLock().lock();
		try {
			if(!configMap.containsKey(configName)){
				Properties properties = FileLoader.loadProByClassPath(configName);
				
				Map<String, Object> config = new HashMap<String, Object>();
				for(Object key : properties.keySet()){
					config.put((String)key, properties.get(key));
				}
				configMap.put(configName, config);
			}
		} finally {
			lock.writeLock().unlock();
		}
	}
	
	/**
	 * 重新加载某个配置文件
	 * @param configName
	 */
	public static void reload(String configName){
		lock.writeLock().lock();
		try {
			configMap.remove(configName);
			init(configName);
		} finally {
			lock.writeLock().unlock();
		}
		
	}
	
	public static Object getValue(String key) {
		return getValue(key, defaultConfig);
	}
	
	public static Object getValue(String key, String configName) {
		lock.readLock().lock();
		try {
			Map<String, Object> config = configMap.get(configName);
			if(config==null){
				init(configName);
			}
			config = configMap.get(configName);
			if(config.containsKey(key)){
				return config.get(key);
			}
		} finally {
			lock.readLock().unlock();
		}
		return null;
	}
	
	public static String getStringValue(String key){
		return (String)getValue(key);
	}
	
	public static String getStringValue(String key, String configName){
		return (String)getValue(key, configName);
	}

	public static int getIntValue(String key) {
		return Integer.valueOf(getStringValue(key));
	}
	
	public static int getIntValue(String key, String configName) {
		return Integer.valueOf(getStringValue(key, configName));
	}
	
}
